package com.vf.admin.common;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.service.AppUserService;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.utils.ResPonseRetUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token拦截过滤
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private AppUserService appUserService;
    @Autowired
    RedisUtil redisUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();//请求地址
        String token = request.getHeader("token");
        if (ObjectUtil.isNotEmpty(token)){
            Object userId = redisUtil.get(RedisKeys.userToken + request.getHeader("token"));
            logger.info("token:" + token);
            if (ObjectUtil.isEmpty(userId)){
                //说明token失效
                Result result = new Result();
                result.setCode(Constants.code_login_error);
                result.setMsg(Constants.msg_return_login);
                ResPonseRetUtil.getInstance().sendJsonMessage(response, result);
                return false;
            }
        }
        return true;
    }
}
